import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  FlatList,
  SectionList,
  TouchableOpacity,
  Image,
  Dimensions,
  Modal,
  ScrollView,
  PanResponder,
  PixelRatio,
  StatusBar,
  KeyboardAvoidingView,
  TextInput,
  ImageBackground,
} from 'react-native';

import MIcon from 'react-native-vector-icons/MaterialIcons';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import { NavigationActions } from 'react-navigation';
import {Avatar, Divider } from 'react-native-elements';
import Button from 'antd-mobile/lib/button';
import CommonStyles from '../../common/styles';
import {AlbumView, Overlay, PullPicker} from 'teaset';
import ScrollableTabView, { ScrollableTabBar, } from 'react-native-scrollable-tab-view';
import RNFetchBlob from 'react-native-fetch-blob';
import Request from '../../common/request';
import Config from '../../common/config';
import Toast from 'react-native-root-toast';
import Util from '../../common/Util';

var ImagePicker = require('react-native-image-picker');


const {width, height} = Dimensions.get('window');

export default class CreateTopic extends React.Component {
  static navigationOptions = (navigation) => {
    return ({
      tabBarVisible: false,
      header: null,
    })
  }

  constructor(props) {
    super(props);
    console.log(Util);
  }

  state = {
    loading: false,
    title: "",
    content: "",
    fid: 1,
    selectedImages: [],
    attachments: [],
    uploadProgressValue: 0,
    uploadProgressText: "待上传",
  }

  gotoTopicDetail() {
    console.log("gotoTopicDetail");
    this.props.navigation.navigate("CommentComment");
  }

  goBack() {
  //  this.props.navigation.navigate("ForumMain");
   this.props.navigation.goBack();
  }
  updateProgress(progressValue, progressText, activeImage) {
    this.setState({uploadProgressValue: progressValue, uploadProgressText: progressText});
  }

  doCreate() {
    let data = {
      title: this.state.title,
      fid: this.state.fid,
    }
    let content = [];
    content.push({
      type: 'text', 
      data: {
        text: this.state.content
      }
    });
    if (this.state.attachments.length) {
      this.state.attachments.map(item => {
        content.push({
          type: "image",
          data: {
            attachment_key: item.key
          }
        })
      })
    }
    data.content = JSON.stringify(content);
    console.log("will do create topic: ", data);
    Request.post(Config.api.topic, data).then((response) => {
      console.log(response);
      Toast.show(response.msg);
      if (response.ret == 0) {
        setTimeout(() => {
          this.goBack();
        }, 3)
      }
    })
  }

  pickPhoto() {
    if (this.state.loading) {
      console.log("loading");
      return;
    }
    if (this.state.attachments.length) {
      console.log("already have attachments");
      return;
    }
    var options = {
      title: 'Select Avatar',
      customButtons: [
        
      ],
      storageOptions: {
        skipBackup: true,
        path: 'images'
      }
    };
    var self = this;
    
    /**
     * The first arg is the options object for customization (it can also be null or omitted for default options),
     * The second arg is the callback which sends object: response (more info below in README)
     */
    ImagePicker.showImagePicker(options, (response) => {
      console.log('Response = ', response);
    
      if (response.didCancel) {
        console.log('User cancelled image picker');
      }
      else if (response.error) {
        console.log('ImagePicker Error: ', response.error);
      }
      else if (response.customButton) {
        console.log('User tapped custom button: ', response.customButton);
      }
      else {
        console.log(response);
        response.key = response.fileName;
        // return;
        
        this.setState({
          selectedImages: [...this.state.selectedImages, response],
          loading: true,
        }, async () => {
          //开始上传
          var token = await Request.getToken();
          var requestOptions = await Request.getRequestOptions('POST');
          console.log("requestOptions: ", requestOptions);
          RNFetchBlob.fetch('POST', Config.api.upload, requestOptions.headers, [
            {
              name: "image", 
              filename: response.fileName, 
              type: "image/jpeg",
              data: RNFetchBlob.wrap(response.origURL)
            }
          ])
          // listen to upload progress event
          .uploadProgress((written, total) => {
            let progress = (written / total) * 100;
            progress = Math.floor(progress);
            console.log('uploaded: ', progress);
            self.updateProgress(progress, "上传中...", response);
          })
          // listen to download progress event
          .progress((received, total) => {
            console.log('downloaded: ', received / total);
          })
          .then((resp) => {
            var result = JSON.parse(resp.data);
            console.log("finished: ", result);
            self.updateProgress(100, "上传完成", response);
            self.setState({
              attachments: [...this.state.attachments, result.data],
              loading: false,
            });
          })
          .catch((err) => {
            console.log('err: ', err);
          })
          

        });
        
      }
    });
  }

  render() {
    let Images = this.state.selectedImages.map((item, i) => {
      return (
        <TouchableOpacity key={item.key}>
          <ImageBackground style={[styles.imageItem]} source={{uri: item.uri}}>
            <Text style={styles.uploadStatus}>{this.state.uploadProgressText}</Text>
            <Text style={styles.uploadStatus}>{this.state.uploadProgressValue}%</Text>
            <View style={[styles.mask, {height: (100 - this.state.uploadProgressValue) + "%"}]}></View>
          </ImageBackground>
        </TouchableOpacity>
      )
    });
    return (
      <KeyboardAvoidingView style={{flex: 1}} behavior="padding">
        <View style={[CommonStyles.container, CommonStyles.row, styles.sectionTopAction]}>
          <TouchableOpacity onPress={() => {this.goBack()}}>
            <Icon name="close" size={20} style={styles.pagetTitleLeft}/>
          </TouchableOpacity>
          <Text>发布到明珠版块</Text>
          <TouchableOpacity onPress={() => {this.doCreate()}}>
            <Text>发布</Text>
          </TouchableOpacity>
        </View>
        <View style={[CommonStyles.container]}>
          <TextInput placeholder="标题" multiline={false} style={styles.title} onChangeText={text => this.setState({"title": text})}/>
          <View style={styles.divider}></View>
          <TextInput placeholder="内容" multiline={true} style={styles.content} onChangeText={text => this.setState({"content": text})}/>
          <View style={[CommonStyles.row]}>
            {Images}
            <TouchableOpacity 
                style={[styles.imageItem, styles.btnAddImage]}
                activeOpacity={0.8}
                onPress={() => this.pickPhoto()}
              >
                <Icon  name="plus" size={50} />
            </TouchableOpacity>
          </View>
        </View>
     </KeyboardAvoidingView>
    )
  }
}

var styles = StyleSheet.create({
  sectionTopAction: {
    paddingTop: 24,
    justifyContent: "space-between",
  },
  pagetTitleLeft: {
    alignSelf: "flex-start"
  },
  sectionHeaderWrapper: {
    paddingBottom: 15,
    marginBottom: 5,
  },
  sectionHeader: {
    alignItems: "center",
    justifyContent: "space-between",
  },
  divider: {
    height: 1,
    backgroundColor: "#eee",
    marginTop: 10,
    marginBottom: 10,
  },
  title: {
    marginTop: 10,
  },
  content: {
   
    height: 100
  },
  imageItem: {
    height: 50,
    width: 50,
    marginRight: 5,
    alignItems: "center",
    justifyContent: "center",
    position: "relative",
  },
  btnAddImage: {
    borderWidth: 1,
    borderColor: "#aaa",
    borderStyle: "dotted",
    alignItems: "center",
    justifyContent: "center",
  },
  uploadStatus: {
    fontSize: 10,
    color: "white",
    backgroundColor: "transparent",
    zIndex: 9999,
    position: "relative",
  },
  mask: {
    position: "absolute",
    left: 0,
    bottom: 0,
    width: "100%",
    height: "100%",
    backgroundColor: "rgba(0, 0, 0, 0.5)",
    zIndex: 999,
  }
})